package com.healthdata.controller;

import com.healthdata.entity.User;
import com.healthdata.entity.UserApplication;
import com.healthdata.service.UserService;
import com.healthdata.util.JwtUtil;
import com.healthdata.vo.UserApplicationVO;
import com.healthdata.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        // 强制设置角色为研究员
        user.setRole(User.ROLE_RESEARCHER);
        boolean success = userService.register(user);
        if (success) {
            // 注册成功，直接生成 token
            User registeredUser = userService.getByUsername(user.getUsername());
            if (registeredUser != null) {
                String token = jwtUtil.generateToken(registeredUser.getId());
                result.put("success", true);
                if(registeredUser.getEmail()==null){
                    result.put("message", "注册成功，已自动登录，没有邮箱无法在忘记密码时验证，请注意及时填写");
                }else {
                    result.put("message", "注册成功，已自动登录");
                }

                result.put("token", token);
                UserVO userVO = convertToUserVO(registeredUser);
                result.put("user", userVO);
            } else {
                result.put("success", false);
                result.put("message", "注册成功，但获取用户信息失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "用户名已存在");
        }
        return result;
    }


    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginInfo) {
        Map<String, Object> result = new HashMap<>();
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");

        String token = userService.login(username, password);
        if (token != null) {
            User user = userService.getByUsername(username);
            result.put("success", true);
            if (user.getStatus() == 0) {
                result.put("message", "该用户存在违规行为，已做封禁处理，除申诉功能外，其他功能全部无法使用，如有疑问可向审核员申诉反馈");
            }else {
                result.put("message", "登录成功");
            }
            result.put("token", token);
            UserVO userVO = convertToUserVO(user);
            result.put("user", userVO);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    private UserVO convertToUserVO(User user) {
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setUsername(user.getUsername());
        userVO.setPassword(user.getPassword());
        userVO.setRole(user.getRole());
        userVO.setEmail(user.getEmail());
        userVO.setPhone(user.getPhone());
        userVO.setStatus(user.getStatus());
        userVO.setCreateTime(user.getCreateTime());
        userVO.setUpdateTime(user.getUpdateTime());
        return userVO;
    }


    @PostMapping("/resetPassword")
    public Map<String, Object> resetPassword(@RequestBody Map<String, String> resetInfo) {
        Map<String, Object> result = new HashMap<>();
        String username = resetInfo.get("username");
        String email = resetInfo.get("email");
        String password = resetInfo.get("newPassword");

        boolean success = userService.resetPassword(username, email,password);
        result.put("success", success);
        result.put("message", success ? "密码重置成功" : "用户名或邮箱错误");
        return result;
    }

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/getUserInfo")
    @PreAuthorize("isAuthenticated()") // 允许所有认证用户访问
    public Map<String, Object> getUserInfo(@RequestHeader("Authorization") String authHeader) {
        Map<String, Object> result = new HashMap<>();

//        // 从 Authorization 头中提取 token
//        String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;


        if (!jwtUtil.verifyToken(authHeader)) {
            result.put("success", false);
            result.put("message", "Token 无效或已过期");
            return result;
        }

        Long userId = jwtUtil.getUserIdFromToken(authHeader);
        if (userId != null) {
            User user = userService.getById(userId);
            if (user.getStatus() == 0) {
                result.put("success", false);
                result.put("message", "该用户存在违规行为，已做封禁处理，无法使用该功能，如有疑问可向审核员申诉反馈");
                return result;
            }
                if (user != null) {
                UserVO userVO = convertToUserVO(user);
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("user", userVO);
            } else {
                result.put("success", false);
                result.put("message", "用户不存在");
            }
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }

    @PostMapping("/updateUserInfo")
    @PreAuthorize("isAuthenticated()") // 允许所有认证用户访问
    public Map<String, Object> updateUserInfo(@RequestBody User user, @RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            user.setId(userId); // 自动设置用户 ID
            User currentUser = userService.getById(userId);
            if (currentUser.getStatus() == 0) {
                result.put("success", false);
                result.put("message", "该用户存在违规行为，已做封禁处理，无法使用该功能，如有疑问可向审核员申诉反馈");
                return result;
            }
            User updateUser = userService.getByUsername(user.getUsername());
            if (updateUser != null) {
                result.put("success", false);
                result.put("message","修改的用户名已存在，信息修改失败");
                return result;
            }
            boolean success = userService.updateById(user);
            if (success) {
                User updatedUser = userService.getById(userId);
                UserVO userVO = convertToUserVO(updatedUser);
                result.put("success", true);
                result.put("message", "信息修改成功");
                result.put("user", userVO);
            } else {
                result.put("success", false);
                result.put("message", "信息修改失败");
            }
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }
}
